﻿using System.Web.Mvc;
using EPiAbstractions.Common.Tags;
using EPiServer.Common.Tags;

namespace JoelAbrahamsson.Web.ModelBinders
{
    public class TagModelBinder : IModelBinder
    {
        private ITagHandlerFacade _tagHandlerFacade;

        public TagModelBinder(ITagHandlerFacade tagHandlerFacade)
        {
            _tagHandlerFacade = tagHandlerFacade;
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string tagName = ParseSlug(controllerContext.RouteData.Values["tagName"].ToString());

            ITag tag = _tagHandlerFacade.GetTag(tagName.ToLower());

            if (tag == null)
                tag = _tagHandlerFacade.GetTag(tagName.ToLower().Replace(" ", "-"));

            return tag;
        }

        private string ParseSlug(string slug)
        {
            return slug
                .Replace("-", " ")
                .Replace("sharp", "#");
        }
    }
}
